package com.heima.behavior.config;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.ApThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * Wm token interceptor
 *
 * @author DiXiaoNie
 * @date 2022/12/21
 * @since 2022 /12/21 15:39 在当前微服务中的拦截器，目的为了从请求头中获取token，然后把用户Id保存到当前线程中
 */
public class TokenInterceptor implements HandlerInterceptor {


    /**
     *
     *在目的方法之前执行该方法拦截
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        //判断token不为空
        Optional<String> optional = Optional.ofNullable(token);
        if (optional.isPresent()) {
            //2.解析token,获取用户id
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            Object userId = claimsBody.get("id");
            //3.存入当前线程中
            ApUser apUser = new ApUser();
            apUser.setId((Integer) userId);
            ApThreadLocalUtil.setApUserThreadLocal(apUser);
        }
        //4.放行
        return Boolean.TRUE;
    }


    /**
     *
     *在目的方法之后执行该方法拦截
     * @param request      请求
     * @param response     响应
     * @param handler      处理程序
     * @param modelAndView 模型和视图
     * @author DiXiaoNie
     * @date 2022/12/21
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ApThreadLocalUtil.deleteApUserThreadLocal();
    }
}
